package com.ling.pl.security.decision;


import com.ling.pl.security.model.DefaultUser;
import com.ling.pl.security.utils.AttributeType;
import com.ling.pl.security.utils.SecurityConfigAttribute;

import java.util.Collection;

/**
 * @author bo.wang
 */
public class UserAccessDecisionVoter extends AbstractAccessDecisionVoter {

    @Override
    protected AttributeType getAttributeType() {
        return AttributeType.user;
    }

    public int vote(DefaultUser authentication, Object object, Collection attributes) {
        for (Object attribute : attributes) {
            SecurityConfigAttribute configAttribute = (SecurityConfigAttribute) attribute;
            boolean granted = configAttribute.isGranted();
            if (!configAttribute.getAttributeType().equals(AttributeType.user)) {
                continue;
            }
            DefaultUser user = (DefaultUser) configAttribute.getMember();
            if (authentication.getUsername().equals(user.getUsername())) {
                if (granted) {
                    return ACCESS_GRANTED;
                } else {
                    return ACCESS_DENIED;
                }
            }
        }
        return ACCESS_ABSTAIN;
    }
}
